package com.charon.common.security.session;

import java.io.Serializable;

import javax.servlet.ServletRequest;

import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

/**
 * @Description:自定义SessionManager，实现将Session缓存到Request中
 * @author:charon [248135724@qq.com]
 * @date: 2018年12月19日 下午10:37:26
 * @verdion V1.0
 */
public class CustomSessionManager extends DefaultWebSessionManager {

	@Override
	protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
		System.out.println("SessionManager执行：写入");
		Serializable sessionId = getSessionId(sessionKey);
		ServletRequest request = null;
		if (sessionKey instanceof WebSessionKey)
			request = ((WebSessionKey) sessionKey).getServletRequest();
		if (request != null && sessionId != null) {
			Session attribute = (Session) request.getAttribute(sessionId.toString());
			System.out.println("	request中是否包含attribute："+(attribute!=null));
			if(attribute!=null)return attribute;
		}
		Session session = super.retrieveSession(sessionKey);
		if (request != null && sessionId != null)
			request.setAttribute(sessionId.toString(), session);
		System.out.println("	执行写入attribute："+sessionId);
		return session;
	}
	
	@Override
	protected void onExpiration(Session s, ExpiredSessionException ese, SessionKey key) {
		System.out.println("SessionManager执行：清除");
		// 首先更新介质中的Session
	    super.onExpiration(s, ese, key);
	    Serializable sessionId = getSessionId(key);
	    ServletRequest request = null;
	    if (key instanceof WebSessionKey)
			request = ((WebSessionKey) key).getServletRequest();
	    if (request != null && sessionId != null) {
			Session attribute = (Session) request.getAttribute(sessionId.toString());
			System.out.println(" 	执行：清除request的session："+(attribute!=null));
			if(attribute!=null)request.removeAttribute(sessionId.toString());
		}
	}
}
